package com.dts.controller;

import com.dts.entity.Hello;
import org.apache.log4j.Logger;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class HelloController {

    private static final Logger logger = Logger.getLogger(HelloController.class);
    @RequestMapping("/hello")
    public String display() {
        int i = 9 / 0;
        return "index";
    }

    @RequestMapping("/dis")
    public String display1(@Validated Hello hello, BindingResult result) {
        if (result.hasErrors()) {
            System.out.println("error:" + result.getAllErrors());
        }
        return "index";
    }

    @RequestMapping("/file")
    public String file(@RequestParam(value = "file") MultipartFile file) {
        if (!file.isEmpty()) {
            System.out.println("file not empty");
            try {
                // 保存文件到指定目录
                String filePath = "D:\\cxdownload\\" + file.getOriginalFilename();
                file.transferTo(new File(filePath));
                return "redirect:/index.jsp";
            } catch (IOException e) {
                e.printStackTrace();
                return "redirect:/error.jsp";
            }
        } else {
            System.out.println("file is empty");
            return "redirect:/error.jsp";
        }
    }

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam("file") String fileName) {
        try {
            Path path = Paths.get("D:\\cxdownload\\" + fileName);
            Resource resource = new UrlResource(path.toUri());
            if (resource.exists() || resource.isReadable()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                throw new RuntimeException("Could not read the file!");
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException("Error: " + e.getMessage());
        }
    }
}